<?php
/**
 * JWT
 */
declare(strict_types=1);

namespace Apps\Http\Hooks;

use Libraries\Bases\HookBase;
use Libraries\Config;
use Firebase\JWT\JWT;
use Exception;
use Libraries\Dispatcher;

class JwtAuth extends HookBase
{
    /**
     * 验证
     * @param string $strToken
     * @param string $strKey
     * @return null or obj
     */
    private static function check(string $strToken, string $strKey)
    {
        if (strlen($strToken) && strlen($strKey)) {
            if (substr($strToken, 0, 7) == 'Bearer ') {
                $strToken = substr($strToken, 7);
            } else {
                $strToken = '';
            }
        }
        if (strlen($strToken)) {
            try {
                JWT::$leeway = 86400; // 一天有效期
                return JWT::decode($strToken, $strKey, ['HS256']);
            } catch (Exception $objE) {
                // do nothing
            }
        }
        return null;
    }
    
    /**
     * Hook
     * @param string $strCtrlAction
     * @param string $strHookType
     * @param array $arrParam
     * @return void
     */
    public function run(string $strCtrlAction = '', string $strHookType = Dispatcher::HOOK_AFTER, array $arrParam = []): void
    {
        $strKey = Config::get('jwt_key_HS256');
        if (!$strKey || $this->objCtrl->blnOutputEnd) {
            return;
        }
        $strToken = ($this->objCtrl->arrHeader['authorization'] ?? '');
        strlen($strToken) || $strToken = ($this->objCtrl->arrCookie['authorization'] ?? '');
        strlen($strToken) || $strToken = ($this->objCtrl->arrPost['authorization'] ?? '');
        $objJwtPayload = self::check($strToken, $strKey);
        if (!is_null($objJwtPayload)) {
            $this->objCtrl->arrHookData['jwt_payload'] = $objJwtPayload;
        }
    }
}
